<template>
  <div class="week_report">
    <el-card style="height:90vh">
      <template #header>
        <div class="card-header">
          <span>本周工作简报</span>
        </div>
      </template>

      <!-- <span style="font-size:14px;color:rgb(165, 27, 27)">（选中下面的日期将出现那天可接单的人）</span> -->
      <div style="display:inline-block;">
        <span
          :style="{ width: '25px', height: '15px', background: colors.level1, display: 'inline-block', borderRadius: '4px', marginRight: '5px' }"></span><span
          style="color:rgb(70, 70, 70)">紧急项目</span>
        <span
          :style="{ width: '25px', height: '15px', background: colors.level2, display: 'inline-block', borderRadius: '4px', margin: '0 5px' }"></span><span
          style="color:rgb(70, 70, 70)">正常项目</span>
        <span
          :style="{ width: '25px', height: '15px', background: colors.level3, display: 'inline-block', borderRadius: '4px', margin: '0 5px' }"></span><span
          style="color:rgb(70, 70, 70)">长期项目</span>
        <span style="font-size:14px;margin-left:10px;color:gray;">（点击项目名称可以操作项目，也可点击序号栏，直接完成项目）</span>
      </div>

      <el-button type="success" class='btn' @click="download">导出本周简报</el-button>
      <el-button type="primary" class='btn' @click="add">新增</el-button>

      <el-table :data="tableData" border height="74vh" style="width: 100%; margin-top: 20px"
        :row-class-name="tableRowClassName" :cell-class-name="handleCellClassName"
        :header-cell-class-name="handleHeaderCellClassName">
        <el-table-column prop="progress" label="序号" width="100" fixed>
          <template #default="scope">
            <el-button round v-if="scope.row.progress !== '100'" @click="showDialog(scope.row.id)">进行中</el-button>
            <el-button round v-if="scope.row.progress === '100'" type="danger">已完成</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="product_name" label="项目名称" width="180" fixed>
          <template #default="scope">
            <el-popover placement="top" width="100" trigger="click" v-if="scope.row.progress !== '100'">
              <el-button size="small" @click="editOrder(scope.row.id)">编辑</el-button>
              <el-button type="danger" size="small" @click="deleteOrder(scope.row.id)">删除</el-button>
              <template #reference>
                <p style="cursor:pointer;" @click="handleClick(scope.row.product_name)">
                  {{ scope.row.product_name }}
                </p>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="member" label="参与人员" width="180" fixed>
          <template #default="scope">
            <el-tag class="ml-2" v-for="name in scope.row.member.split(',')" :key="name" @click="nameClick(name)">{{ name
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="department_name" label="部门" width="150" />
        <el-table-column prop="notes" label="备注" width="200">
          <template #default="scope">
            <span v-html="formatRemark(scope.row.notes)"></span>
          </template>
        </el-table-column>
        <!-- 日期列 -->
        <el-table-column v-for="(date, index) in dateList" :key="index" :label="formatDateWithDay(date)" :min-width="100"
          :width="auto" align="center">
          <template #default="scope">
            <!-- 如果不是周末，显示色块 -->
            <div v-if="!isWeekend(date) && isDateInRange(date, scope.row.work_date, scope.row.deadline_date)" :style="{
              backgroundColor: getTaskColor(scope.row.level),
              // borderRadius: '4px',
              width: '100%',
              height: '100%',
              position: 'absolute',
              top: '0',
              left: '0',
              padding: '0',
              margin: '0',
              zIndex: scope.row.level ? 4 - scope.row.level : 1
            }" class="task-block">
            </div>
            <!-- 添加可编辑文本框 -->
            <div style="position:absolute;z-index:3;width:100%;height:100%;top:0;
            left:0">
              <!-- 可编辑输入框 -->
              <el-input v-if="isEditingCell(scope.row, date)" v-model="editableText"
                @keydown.enter.prevent="handleEnter(scope.row, date)" @keydown.esc="handleEsc(scope.row, date)"
                size="mini" ref="inputRef" @input="handleInput" type="textarea" style="width: 100%;height:100%"
                class="inputText" />

              <!-- 静态展示内容 -->
              <div v-if="getEditableText(scope.row, date)" @click="activateEditing(scope.row, date)"
                style="width: 100%; height: 100%; cursor: pointer; display: flex; align-items: center; justify-content: center; overflow: hidden;">
                <el-tooltip :content="getEditableText(scope.row, date)" placement="right"
                  :popper-style="{ maxWidth: '200px', whiteSpace: 'normal' }" 
                  >
                  <p style="margin: 0; font-size: 12px;">{{ getEditableText(scope.row, date) }}</p>
                </el-tooltip>
              </div>

              <div v-else @click="activateEditing(scope.row, date)"
                style="width: 100%; height: 100%; cursor: pointer; display: flex; align-items: center; justify-content: center; overflow: hidden;">
                <p style="margin: 0; font-size: 12px;">{{ getEditableText(scope.row, date) || '' }}</p>
              </div>
            </div>
          </template>
        </el-table-column>

        <!-- <el-table-column label="操作" width="160">
          <template #default="scope">
            <el-button size="small" @click="editOrder(scope.row.id)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteOrder(scope.row.id)">删除</el-button>
          </template>
        </el-table-column> -->
      </el-table>
      <el-dialog v-model="dialogTableVisible" title="选择文件数量" width="304">
        <el-form ref="form" :model="formData" class="el-group-complete">
          <el-form-item label="海报设计：" label-width="93px">
            <el-input-number v-model="formData.haibao" :min="0" style="width: 150px" />
          </el-form-item>

          <el-form-item label="长图设计：" label-width="93px">
            <el-input-number v-model="formData.changtu" :min="0" style="width: 150px" />
          </el-form-item>

          <el-form-item label="H5设计：" label-width="93px">
            <el-input-number v-model="formData.h5" :min="0" style="width: 150px" />
          </el-form-item>

          <el-form-item label="视频制作：" label-width="93px">
            <el-input-number v-model="formData.shipin" :min="0" style="width: 150px" />
          </el-form-item>
          <el-form-item label="资源图：" label-width="93px">
            <el-input-number v-model="formData.ziyuan" :min="0" style="width: 150px" />
          </el-form-item>

          <el-form-item label="插画：" label-width="93px">
            <el-input-number v-model="formData.chahua" :min="0" style="width: 150px" />
          </el-form-item>

          <el-form-item label="动画：" label-width="93px">
            <el-input-number v-model="formData.donghua" :min="0" style="width: 150px" />
          </el-form-item>

          <el-form-item label="PPT杂志：" label-width="93px">
            <el-input-number v-model="formData.ppt" :min="0" style="width: 150px" />
          </el-form-item>

          <el-form-item label="物料：" label-width="93px">
            <el-input-number v-model="formData.wuliao" :min="0" style="width: 150px" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer" style="text-align: center;margin-top:-20px;margin-bottom:20px">
            <el-button type="primary" @click="goComplete()">
              确定
            </el-button>
            <el-button @click="cancel()">取消</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import workApi from '../../api/work'
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
const router = useRouter()
const dialogTableVisible = ref(false)
const colors = {
  level1: '#fbe4d2',
  level2: '#e4f2d9',
  level3: '#fff3c9'
}
// Dom 挂载之后
onMounted(() => {
  getRecentWorks()
})
// 数据
const tableData = ref([])

const username = sessionStorage.getItem('username')

// form
const formData = reactive({
  id: '',
  haibao: '',
  changtu: '',
  h5: '',
  shipin: '',
  ziyuan: '',
  chahua: '',
  donghua: '',
  ppt: '',
  wuliao: '',
  work_date: '',
  deadline_date: '',
  username: username
})


// 获取最近工作列表
const getRecentWorks = async () => {
  const res = await workApi.getRecentWorks()
  console.log(res.data)
  if (res.status == 200) {
    tableData.value = res.data

    console.log(res.data)

    // 将已完成的数据放到最后面
    tableData.value = tableData.value.sort((a, b) => {
      return a.progress === '100' ? 1 : b.progress === '100' ? -1 : 0
    })
  }
}


const tableRowClassName = (row, rowIndex) => {
  if (row.row.progress === '100') {
    return 'warning-row'
  }
  return ''
}

const add = async () => {
  router.push({
    path: '/week_report/add',
  })
}

const editOrder = async (id) => {
  router.push({
    path: '/week_report/add',
    query: { id: id },
  })
}

const customSortMethod = (a, b) => {
  const progressA = parseInt(a.progress)
  const progressB = parseInt(b.progress)

  // 正常排序
  return progressA - progressB
}

// 删除项目
const deleteOrder = (id) => {
  ElMessageBox.confirm('确定要删除该项目吗?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const username = sessionStorage.getItem('username')
      const res = await workApi.delOrder({ id: id, username: username })
      if (res.data.success) {
        ElMessage.success('删除成功')
        getRecentWorks()
      } else {
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

const nameClick = async (name) => {
  router.push({
    path: '/member_report',
  });
}

const download = async () => {
  const lastSaturday = getLastSaturday();
  const nextSaturday = getNextSaturday();
  const lastSaturdayFormatted = formatDate(lastSaturday);
  const nextSaturdayFormatted = formatDate(nextSaturday);

  const data = tableData.value.map((item, index) => {
    let result = ''
    if (item.progress === '100') {
      result = `${index + 1}. ${item.department_name}（已完成）：${item.product_name}`;
    } else {
      result = `${index + 1}. ${item.department_name}：${item.product_name}`;
    }
    if (item.notes) {
      result += `，${item.notes}`
    }
    return result;
  }).join('\r\n');

  // 创建 Blob 对象，确保 MIME 类型为 text/plain
  const blob = new Blob([data], { type: 'text/plain;charset=utf-8' });

  // 创建下载链接并触发下载
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = `${lastSaturdayFormatted}__${nextSaturdayFormatted}_简报.txt`;
  link.click();

  // 释放 URL 对象
  URL.revokeObjectURL(link.href);
}

const getLastSaturday = () => {
  const today = new Date();
  const dayOfWeek = today.getDay();
  const lastSaturday = new Date(today);
  lastSaturday.setDate(today.getDate() - dayOfWeek - 1);
  if (dayOfWeek === 0) {
    lastSaturday.setDate(lastSaturday.getDate() - 7);
  }
  return lastSaturday;
};

const getNextSaturday = () => {
  const today = new Date();
  const dayOfWeek = today.getDay();
  const diff = 6 - dayOfWeek;
  const nextSaturday = new Date(today);
  nextSaturday.setDate(today.getDate() + diff);
  return nextSaturday;
};

const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

const formatDate1 = (d) => {
  const localDate = new Date(d);
  localDate.setHours(localDate.getHours() + 8); // Convert UTC to China timezone
  const year = localDate.getFullYear();
  const month = String(localDate.getMonth() + 1).padStart(2, '0'); // Months are 0-indexed
  const day = String(localDate.getDate()).padStart(2, '0');

  return `${year}-${month}-${day}`;
};
const showDialog = (id) => {
  dialogTableVisible.value = true
  formData.id = id
}
const goComplete = async () => {
  ElMessageBox.confirm('确定完成吗?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const res = await workApi.goComplete(formData)
      if (res.data.success) {
        ElMessage.success('更新成功')
        cancel()
        getRecentWorks()
      } else {
        ElMessage.error('更新失败')
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

const cancel = () => {
  dialogTableVisible.value = false
  Object.assign(formData, {
    id: '',
    haibao: '',
    changtu: '',
    h5: '',
    shipin: '',
    ziyuan: '',
    chahua: '',
    donghua: '',
    ppt: '',
    wuliao: '',
    username: username
  });
}


// 获取任务颜色
const getTaskColor = (level) => {
  if (level == "1") {
    return colors.level1
  } else if (level == "2") {
    return colors.level2
  } else if (level == "3") {
    return colors.level3
  } else {
    return colors.level2
  }
}

// 格式化日期和星期
const formatDateWithDay = (date) => {
  const dayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  const day = dayNames[date.getDay()];
  return `${date.toLocaleDateString('zh-CN', { day: '2-digit' })} ${day}`;
};

// 获取今天前1天和后29天的日期
const getDateRange = () => {
  const today = new Date();
  const start = new Date(today);
  start.setDate(today.getDate() - 1);
  const end = new Date(today);
  end.setDate(today.getDate() + 29);

  const dates = [];
  let current = new Date(start);

  while (current <= end) {
    dates.push(new Date(current));
    current.setDate(current.getDate() + 1);
  }

  return dates;
};

const dateList = ref(getDateRange());

// 判断任务是否在日期范围内
const isDateInRange = (date, startDate, endDate) => {
  // 创建新的 endDate 对象并将其增加一天
  const adjustedEndDate = new Date(endDate);
  adjustedEndDate.setDate(adjustedEndDate.getDate() + 1);

  return date >= new Date(startDate) && date <= adjustedEndDate;
};

// 判断是否为周末
const isWeekend = (date) => {
  if (!date) {
    return false; // 如果 date 为空，直接返回 false
  }

  const day = date.getDay();
  return day === 0 || day === 6; // 周日(0)和周六(6)是周末
};

const isToday = (date) => {
  const today = new Date()
  return date.getDate() === today.getDate() && date.getMonth() === today.getMonth() && date.getFullYear() === today.getFullYear()
}

// 修改 handleCellClassName 函数，给周末列加灰色背景，同时为当前日期列高亮
const handleCellClassName = ({ rowIndex, columnIndex }) => {
  const date = dateList.value[columnIndex - 5]; // 假设日期列从第5列开始

  if (!date) {
    return ''; // 如果 date 为空，不应用任何类名
  }

  // 如果是周末，返回灰色背景
  if (isWeekend(date)) {
    return 'weekend-column';
  }

  // 如果是今天的日期，返回高亮类名
  if (isToday(date)) {
    return 'highlight-today-column';
  }

  return '';
};

// 修改 handleHeaderCellClassName 函数，给表头中的周末列加灰色背景，同时为当前日期表头加高亮
const handleHeaderCellClassName = ({ columnIndex }) => {
  const date = dateList.value[columnIndex - 5]; // 假设日期列从第5列开始

  if (!date) {
    return ''; // 如果 date 为空，不应用任何类名
  }

  // 如果是周末，返回灰色背景
  if (isWeekend(date)) {
    return 'weekend-header';
  }

  // 如果是今天的日期，返回高亮类名
  if (isToday(date)) {
    return 'highlight-today-header';
  }

  return '';
};


const formatRemark = (remark) => {
  if (!remark) return '';

  // 正则表达式匹配 URL
  const urlPattern = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;

  // 将 URL 替换为超链接并替换换行符为 <br>
  return remark
    .replace(urlPattern, (url) => `<a href="${url}" target="_blank">${url}</a>`)
    .replace(/\n/g, '<br>');
};

const handleClick = async (name) => {
  // 这里可以保留原有逻辑或者改为打开弹框逻辑
  console.log('Clicked project:', name);
};


// 追踪当前编辑的状态和内容
const editingKey = ref(null);  // 当前正在编辑的单元格的唯一标识
const editableText = ref('');  // 当前单元格的文本内容

const inputRef = ref(null);  // 输入框的引用，用于聚焦

// 激活某个单元格的编辑模式
const activateEditing = (row, date) => {
  const formattedDate = formatDate(date);  // 格式化 date 参数
  editingKey.value = `${row.id}-${date}`;  // 设置正在编辑的单元格的唯一标识

  // 使用 find 方法查找对应的 textItem，确保返回值存在
  const textItem = row.textList.find(textItem => formatDate1(textItem.date) === formattedDate);

  // 如果 textItem 存在，则使用 textItem.text，否则初始化为空字符串
  editableText.value = textItem ? textItem.text : '';
};


// 判断某个单元格是否处于编辑模式
const isEditingCell = (row, date) => {
  return editingKey.value === `${row.id}-${date}`;
};

// 获取当前单元格的显示文本内容
const getEditableText = (row, date) => {
  // 检查 textList 是否存在且为数组
  if (Array.isArray(row.textList)) {
    // 格式化传入的 date
    const formattedDate = formatDate(date);

    // 查找 textList 中 date 对应的条目
    const matchingText = row.textList.find(textItem => formatDate1(textItem.date) === formattedDate);

    // 如果找到匹配的 textItem，返回其 text，否则返回 null
    if (matchingText) {
      return matchingText.text;
    }
  }

  // 如果 textList 不存在或没有匹配，返回 row[date]，或者返回空字符串作为默认值
  return row[date] || '';
};

const handleEsc = (row, date) => {
  // 将当前编辑的单元格重置为空字符串或者其他非有效值
  if (editingKey.value === `${row.id}-${date}`) {
    editingKey.value = '';  // 退出编辑模式
  }
};


// 处理输入时的文本更新
const handleInput = (value) => {
  editableText.value = value;
};


// 处理按下 Enter 键提交
const isSubmitting = ref(false);  // 标志位，防止重复提交
const handleEnter = async (row, date) => {
  if (isSubmitting.value) return;  // 如果已经在提交，退出函数
  isSubmitting.value = true;  // 设置标志位，开始提交
  editingKey.value = null;  // 退出编辑模式
  const workDate = new Date(date);
  try {
    const updatedData = {
      work_order_id: row.id,
      text: editableText.value,
      date: formatDateToLocalString(workDate),
      username: username
    };

    // 调用 API 提交更新
    await workApi.updateTaskText(updatedData);
    console.log(editableText.value)

    // 只更新当前单元格的值
    row[date] = editableText.value;
    let index = row.textList.findIndex(textItem => formatDate1(textItem.date) === updatedData.date);
    if (index !== -1) {
      row.textList[index].text = editableText.value;
    } else {
      row.textList.push(updatedData);
    }

    isSubmitting.value = false;  // 设置标志位，开始提交
  } catch (error) {
    console.error('数据提交失败:', error);
  }
};

const formatDateToLocalString = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');

  return `${year}-${month}-${day}`;
};

</script>

<style>
.week_report .btn {
  float: right;
  margin-bottom: 20px;
  margin-right: 10px
}

.week_report .el-table .cell {
  text-align: center;
  line-height: 100%;
}

.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.el-tag.ml-2 {
  margin: 4px;
  cursor: pointer;
}

.el-table thead tr {
  font-size: 17px;
}

.el-progress-circle {
  width: 50px !important;
  height: 50px !important;
}

.el-progress__text span {
  font-size: 13px;
}

.el-group-complete .files {
  margin: 10px 40px;
  padding: 30px;
  border-radius: 20px;
  background: rgb(255 255 255);
  box-shadow: rgba(0, 0, 0, 0.45) 0px 5px 40px 0px;
  max-width: 600px;
  width: 300px;
}

.right-aligned-label .el-form-item__label {
  text-align: right;
  display: block;
  width: auto;
  /* Ensure label width adapts to its content */
}

.highlight-today-column {
  border-left: 2px solid green !important;
  border-right: 2px solid green !important;
}

.highlight-today-header {
  border-left: 2px solid green !important;
  border-right: 2px solid green !important;
  border-top: 10px solid green !important;
}

/* 表头周末背景色 */
.weekend-header {
  background-color: #EFEFEF !important;
  color: rgb(173, 173, 173) !important;
}

/* 周末列的灰色背景 */
.weekend-column {
  /* background-color: #EFEFEF !important; */
}

.el-table .cell {
  font-size: 15px;
}

.project-name-wrap {
  word-wrap: break-word;
  /* 长单词折行 */
  word-break: break-all;
  /* 强制折行 */
  white-space: normal;
  /* 允许文本换行 */
  text-align: left;
  /* 项目名称左对齐 */
}

/* .week_report .el-table .el-table__cell {
  padding: 0px !important;
} */

.inputText textarea {
  height: 100%;
}

.week_report .el-table td.el-table__cell, .el-table th.el-table__cell.is-leaf{
  border-bottom:1px solid #8b8888;
}

.week_report .el-table--border .el-table__cell{
  border-right:1px solid #8b8888;
}

.week_report .el-table--border .el-table__inner-wrapper{
  border:1px solid #8b8888;
}
</style>
